#!/usr/bin/env python
#-*- coding:utf-8 -*-

from __future__ import with_statement

import os
import socket
import encoder.pipe

__all__ = ("Controller", "getList", "getPath")


class Controller:

    def makeList(self):
        """ Funcao que cria a lista de arquivos compartilhadas no
            computador do usuario. """

        idArray = []

        # Cria o endereco das pastas que serao utilizadas no programa
        cwd = os.getcwd()
        thisPath = os.path.join(cwd, "media")
        audioPath = os.path.join(thisPath, "audio")
        imagePath = os.path.join(thisPath, "image")
        videoPath = os.path.join(thisPath, "video")

        # Verifica se os diretorios ja existem senao os criam
        if not os.path.exists(thisPath):
            os.mkdir(thisPath)
        if not os.path.exists(audioPath):
            os.mkdir(audioPath)
        if not os.path.exists(imagePath):
            os.mkdir(imagePath)
        if not os.path.exists(videoPath):
            os.mkdir(videoPath)

        default_path = os.getcwd()

        # Abre o arquivo
        with open("echoes.list", "w") as listFile:
            with open("echoes.html", "w") as htmlFile:

                for line in open("sonarhtml.head"):
                    htmlFile.write(line)

                os.chdir(thisPath)
                audioFiles = os.listdir(audioPath)
                imageFiles = os.listdir(imagePath)
                videoFiles = os.listdir(videoPath)

                SharedFilesId = 0

                # --------------------------------------------------- #
                # Navega por todos os arquivos da pasta de video para #
                #          criar o XML deste tipo de arquivo          #
                # --------------------------------------------------- #
                listFile.write("<videos>\n")

                for line in open("..\\sonarhtmlvideo.head"):
                    htmlFile.write(line)

                for root, dirs, filesnames in os.walk(videoPath):
                    for eachVideoFile in videoFiles:

                        path = os.path.join(root, eachVideoFile)
                        (head, tail) = os.path.split(path)
                        (headhead, headtail) = os.path.split(head)
                        (hhead, hhtail) = os.path.split(headhead)

                        pasta = hhtail + "\\" + headtail
                        id = SharedFilesId
                        arquivo = tail

                        if os.path.exists(path):
                            media_info = {}#mediainfo_obj.getInfo(0, path)
                            if media_info.has_key("name") and not media_info["name"] == "":
                                nome = media_info["name"]
                                nome = nome.upper()
                            else:
                                (nome, ext) = os.path.splitext(arquivo)
                                nome = nome.upper()
                            if media_info.has_key("res"): res = media_info["res"]
                            else: res = ""
                        else:
                            nome = ""
                            res = ""

                        ipAdress = socket.gethostbyname(socket.gethostname())
                        req_string = "http://" + str(ipAdress) + ":2323/media.get?id=" + str(id)

                        ctrl = "<video folder=\"" + pasta + "\" id=\"" + str(id) + "\" name=\"" + nome + "\" file=\"" + arquivo + "\" res=\"" + res + "\" />\n"
                        listFile.write(ctrl)

                        htmlFile.write("    <tr>\n")
                        htmlFile.write("        <td class=\"style1\" colspan=\"2\"><b>" + nome + "</b></td>\n")
                        htmlFile.write("    </tr>\n")
                        htmlFile.write("    <tr>\n")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Folder</td>\n")
                        htmlFile.write("        <td class=\"style1\">" + pasta + "</td>\n")
                        htmlFile.write("    </tr>\n")
                        htmlFile.write("    <tr>\n")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Filename</td>\n")
                        htmlFile.write("        <td class=\"style1\">" + arquivo + "</td>\n")
                        htmlFile.write("    </tr>\n")
                        htmlFile.write("    <tr>\n")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Resolution</td>\n")
                        htmlFile.write("        <td class=\"style1\">" + res + "</td>\n")
                        htmlFile.write("    </tr>\n")
                        htmlFile.write("    <tr>\n")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Get it!</td>\n")
                        htmlFile.write("        <td class=\"style1\"><a href=" + req_string + "><span class=\"style7\">" + req_string + "</span></a>\n")
                        htmlFile.write("    </tr>\n")
                        htmlFile.write("    <tr>\n")
                        htmlFile.write("        <td class=\"style1\" colspan=\"2\">-</td>\n")
                        htmlFile.write("    </tr>\n")

                        idArray.insert(SharedFilesId, [eachVideoFile, os.path.join(root, eachVideoFile), 0])
                        SharedFilesId = SharedFilesId + 1

                listFile.write("</videos>\n\n")

                for line in open("..\\sonarhtmlvideo.tail"):
                    htmlFile.write(line)

                # --------------------------------------------------- #
                # Navega por todos os arquivos da pasta de audio para #
                #          criar o XML deste tipo de arquivo          #
                # --------------------------------------------------- #
                listFile.write("<music>\n")

                for line in open("..\\sonarhtmlaudio.head"):
                    htmlFile.write(line)

                for root, dirs, filesnames in os.walk(audioPath):
                    for eachAudioFile in filesnames:
                        path = os.path.join(root, eachAudioFile)
                        (head, tail) = os.path.split(path)

                        id = SharedFilesId
                        arquivo = tail

                        if os.path.exists(path):
                            media_info = {}#mediainfo_obj.getInfo(1, path)
                            if media_info.has_key("artist"):
                                artista = media_info["artist"]
                                artista = artista.title()
                            else: artista = ""
                            if media_info.has_key("album"):
                                album = media_info["album"]
                                album = album.title()
                            else: album = ""
                            if media_info.has_key("title"): musica = media_info["title"]
                            else:
                                (musica, ext) = os.path.splitext(arquivo)
                                musica = musica.upper()
                        else:
                            artista = ""
                            album = ""
                            musica = ""

                        ipAdress = socket.gethostbyname(socket.gethostname())
                        req_string = "http://" + str(ipAdress) + ":2323/media.get?id=" + str(id)

                        ctrl = "<song id=\"" + str(id) + "\" artist=\"" + artista + "\" album=\"" + album + "\" title=\"" + musica + "\" file=\"" + arquivo + "\" />\n"
                        listFile.write(ctrl)

                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\" colspan=\"2\"><b>" + musica + "</b></td>")
                        htmlFile.write("    </tr>")
                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Artist</td>")
                        htmlFile.write("        <td class=\"style1\">" + artista + "</td>")
                        htmlFile.write("    </tr>")
                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Album</td>")
                        htmlFile.write("        <td class=\"style1\">" + album + "</td>")
                        htmlFile.write("    </tr>")
                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">filename</td>")
                        htmlFile.write("        <td class=\"style1\">" + arquivo + "</td>")
                        htmlFile.write("    </tr>")
                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\" style=\"width: 130px\">Get it!</td>")
                        htmlFile.write("        <td class=\"style1\"><a href=" + req_string + "><span class=\"style7\">" + req_string + "</span></a></td>")
                        htmlFile.write("    </tr>")
                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\" colspan=\"2\">-</td>")
                        htmlFile.write("    </tr>")

                        idArray.insert(SharedFilesId, [eachVideoFile, os.path.join(root, eachAudioFile), 1])
                        SharedFilesId = SharedFilesId + 1

                listFile.write("</music>\n\n")

                for line in open("..\\sonarhtmlaudio.tail"):
                    htmlFile.write(line)

                # --------------------------------------------------- #
                # Navega por todos os arquivos da pasta de fotos para #
                #          criar o XML deste tipo de arquivo          #
                # --------------------------------------------------- #
                listFile.write("<pictures>\n")

                for line in open("..\\sonarhtmlimage.head"):
                    htmlFile.write(line)

                for root, dirs, filenames in os.walk(imagePath):
                    for eachImageFile in imageFiles:
                        path = os.path.join(root, eachImageFile)
                        (head, tail) = os.path.split(path)
                        (headhead, headtail) = os.path.split(head)

                        id = SharedFilesId
                        album = headtail
                        arquivo = tail

                        if os.path.exists(path):
                            media_info = {}#mediainfo_obj.getInfo(2, path)
                            if media_info.has_key("res"): res = media_info["res"]
                            else: res = ""
                        else:
                            res = ""

                        ipAdress = socket.gethostbyname(socket.gethostname())
                        req_string = "http://" + str(ipAdress) + ":2323/media.get?id=" + str(id)

                        ctrl = "<pic id=\"" + str(id) + "\" album=\"" + album + "\" file=\"" + arquivo + "\" res=\"" + res + "\" />\n"
                        listFile.write(ctrl)

                        htmlFile.write("    <tr>")
                        htmlFile.write("        <td class=\"style1\">" + album + "</td>")
                        htmlFile.write("        <td class=\"style1\">" + arquivo + "</td>")
                        htmlFile.write("        <td class=\"style1\"><a href=" + req_string + "><span class=\"style7\">Get it!</span></a></td>")
                        htmlFile.write("    </tr>")

                        idArray.insert(SharedFilesId, [eachImageFile, os.path.join(root, eachImageFile), 2])
                        SharedFilesId = SharedFilesId + 1

                listFile.write("</pictures>\n")

                for line in open("..\\sonarhtmlimage.tail"):
                    htmlFile.write(line)

                for line in open("..\\sonarhtml.tail"):
                    htmlFile.write(line)

        os.chdir(default_path)
        return idArray
    # makeList()

# Controller()


def getList():
    control = Controller()
    return control.makeList()
# getList -> será substituída por parseXmlList
# getList -> retorna um array

def getPath(idFile):
    id = int(idFile)
    idArray = getList()
    if id < idArray.__len__():
        path = idArray[id][1]
        return path
    else:
        return -1

def getMediaType(idFile):
    id = int(idFile)
    idArray = getList()
    if id < idArray.__len__():
        type = idArray[id][2]
        return type
    else:
        return -1